import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from '../utils/request'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const userInfo = ref({})
  const isLoggedIn = ref(false)

  const login = async (loginData) => {
    try {
      const response = await axios.post('/api/auth/login', loginData)
      if (response.data.code === 200) {
        token.value = response.data.data.token
        userInfo.value = response.data.data
        isLoggedIn.value = true
        
        // 保存到本地存储
        localStorage.setItem('token', token.value)
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        
        return response.data
      }
      throw new Error(response.data.message)
    } catch (error) {
      throw error
    }
  }

  const logout = async () => {
    try {
      await axios.post('/api/auth/logout')
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 清除状态和本地存储
      token.value = ''
      userInfo.value = {}
      isLoggedIn.value = false
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }

  const initializeAuth = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')
    
    if (savedToken && savedUserInfo) {
      token.value = savedToken
      userInfo.value = JSON.parse(savedUserInfo)
      isLoggedIn.value = true
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    initializeAuth
  }
}) 